package com.caochenlei.codebuilder.main;

import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;

import com.caochenlei.codebuilder.config.DatabaseConfigUtil;
import com.caochenlei.codebuilder.config.KVConfigUtil;
import com.caochenlei.codebuilder.entity.Database;
import com.caochenlei.codebuilder.utils.Alias;
import com.caochenlei.codebuilder.utils.Code;
import com.caochenlei.codebuilder.utils.FileUtil;
import com.caochenlei.codebuilder.utils.PackageUtil;
import com.caochenlei.codebuilder.utils.SystemUtil;
import com.caochenlei.codebuilder.utils.TemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CodeBuilder {
	private static Logger logger = LoggerFactory.getLogger(CodeBuilder.class);

	private JFrame codeBuilderFrame;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;
	private JTextField textField_5;
	private JTextField textField_6;

	private String createPath = SystemUtil.getDefaultCreatePath();

	private Map<String, String> globalMap = new TreeMap<String, String>(new Comparator<String>() {
		@Override
		public int compare(String obj1, String obj2) {
			return obj1.compareTo(obj2);
		}
	});

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		/**
		 * Use the current system skin.
		 */
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}

		/**
		 * Initialize the form and start it.
		 */
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					CodeBuilder window = new CodeBuilder();
					window.codeBuilderFrame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public CodeBuilder() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		codeBuilderFrame = new JFrame();
		codeBuilderFrame.setTitle("CodeBuilder");
		codeBuilderFrame.setBounds(760, 290, 490, 360);
		codeBuilderFrame.setResizable(false);
		codeBuilderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		codeBuilderFrame.getContentPane().setLayout(null);

		// 监听窗口关闭
		codeBuilderFrame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent windowEvent) {
				new File(SystemUtil.getConfigAbsolutePathByName("database")).delete();
				new File(SystemUtil.getConfigAbsolutePathByName("project")).delete();
				new File(SystemUtil.getConfigAbsolutePathByName("generatorConfigurationCustom")).delete();
			}
		});

		final JComboBox<String> comboBox = new JComboBox<String>();
		comboBox.setBounds(89, 270, 280, 30);
		codeBuilderFrame.getContentPane().add(comboBox);
		for (String templateName : TemplateUtil.getAllTemplateNames()) {
			comboBox.addItem(templateName);
		}

		JSeparator separator_1 = new JSeparator();
		separator_1.setBounds(0, 53, 490, 2);
		codeBuilderFrame.getContentPane().add(separator_1);

		JSeparator separator_2 = new JSeparator();
		separator_2.setBounds(0, 255, 490, 2);
		codeBuilderFrame.getContentPane().add(separator_2);

		JLabel label_1 = new JLabel("模板名称：");
		label_1.setBounds(23, 270, 99, 30);
		codeBuilderFrame.getContentPane().add(label_1);

		JLabel label_2 = new JLabel("生成路径：");
		label_2.setBounds(23, 10, 99, 30);
		codeBuilderFrame.getContentPane().add(label_2);

		JLabel label_3 = new JLabel("工程名称：");
		label_3.setBounds(23, 65, 66, 30);
		codeBuilderFrame.getContentPane().add(label_3);

		JLabel label_4 = new JLabel("工程描述：");
		label_4.setBounds(23, 100, 66, 30);
		codeBuilderFrame.getContentPane().add(label_4);

		JLabel label_5 = new JLabel("工程作者：");
		label_5.setBounds(23, 137, 66, 30);
		codeBuilderFrame.getContentPane().add(label_5);

		JLabel label_6 = new JLabel("工程版本：");
		label_6.setBounds(23, 177, 66, 30);
		codeBuilderFrame.getContentPane().add(label_6);

		JLabel label_7 = new JLabel("工程包名：");
		label_7.setBounds(23, 214, 66, 30);
		codeBuilderFrame.getContentPane().add(label_7);

		textField_1 = new JTextField();
		textField_1.setColumns(10);
		textField_1.setBounds(89, 11, 280, 30);
		textField_1.setEditable(false);
		codeBuilderFrame.getContentPane().add(textField_1);
		textField_1.setText(createPath);

		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(89, 65, 360, 30);
		codeBuilderFrame.getContentPane().add(textField_2);
		textField_2.setText("business");

		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(89, 100, 360, 30);
		codeBuilderFrame.getContentPane().add(textField_3);
		textField_3.setText("This is an example project.");

		textField_4 = new JTextField();
		textField_4.setColumns(10);
		textField_4.setBounds(89, 137, 360, 30);
		codeBuilderFrame.getContentPane().add(textField_4);
		textField_4.setText("author");

		textField_5 = new JTextField();
		textField_5.setColumns(10);
		textField_5.setBounds(89, 177, 360, 30);
		codeBuilderFrame.getContentPane().add(textField_5);
		textField_5.setText("1.0.0");

		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(89, 214, 360, 30);
		codeBuilderFrame.getContentPane().add(textField_6);
		textField_6.setText("com.company.business");

		JButton button_1 = new JButton("...");
		button_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent mouseEvent) {
				String defaultPath = textField_1.getText();
				textField_1.setText(FileUtil.selectDirPath("选择代码生成路径", defaultPath));
			}
		});
		button_1.setBounds(370, 10, 80, 32);
		codeBuilderFrame.getContentPane().add(button_1);

		JButton button_2 = new JButton("一键生成");
		button_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent mouseEvent) {
				// ============================== * 工程变量开始 * ==============================
				String project = textField_2.getText().trim();
				String projectComment = textField_3.getText().trim();
				String projectAuthor = textField_4.getText().trim();
				String projectVersion = textField_5.getText().trim();
				String packageName = textField_6.getText().trim();
				String pathAll = PackageUtil.getPathAll(packageName);
				Map<String, String> pathN = PackageUtil.getPathN(packageName);

				globalMap.put("project", project);
				globalMap.put("projectComment", projectComment);
				globalMap.put("projectAuthor", projectAuthor);
				globalMap.put("projectVersion", projectVersion);
				globalMap.put("packageName", packageName);
				globalMap.put("pathAll", pathAll);
				globalMap.putAll(pathN);
				// ============================== * 工程变量结束 * ==============================

				// ============================== * 数据库变量开始 * ==============================
				Database database = DatabaseConfigUtil.read("database");
				String dbIp = database.getDbIp();
				String dbPort = database.getDbPort();
				String dbName = database.getDbName();
				String dbUrl = database.getDbUrl();
				String dbUser = database.getDbUser();
				String dbPassword = database.getDbPassword();
				String dbType = database.getDbType();
				String dbDriverName = database.getDbDriverName();
				String dbDataSourceType = database.getDbDataSourceType();
				String dbDialect = database.getDbDialect();
				String dbGenerator = database.getDbGenerator();

				globalMap.put("dbIp", dbIp);
				globalMap.put("dbPort", dbPort);
				globalMap.put("dbName", dbName);
				globalMap.put("dbUrl", dbUrl);
				globalMap.put("dbUser", dbUser);
				globalMap.put("dbPassword", dbPassword);
				globalMap.put("dbType", dbType);
				globalMap.put("dbDriverName", dbDriverName);
				globalMap.put("dbDataSourceType", dbDataSourceType);
				globalMap.put("dbDialect", dbDialect);
				globalMap.put("dbGenerator", dbGenerator);
				// ============================== * 数据库变量结束 * ==============================

				// ============================== * 路径变量开始 * ==============================
				String templatePath = TemplateUtil.getAbsolutePathByTemplateName(comboBox.getSelectedItem().toString());
				globalMap.put("templatePath", templatePath);
				globalMap.put("projectTemplatePath", templatePath + "\\工程模板");
				globalMap.put("tableTemplatePath", templatePath + "\\表级模板");
				globalMap.put("columnTemplatePath", templatePath + "\\列级模板");
				globalMap.put("createPath", textField_1.getText());
				// ============================== * 路径变量结束 * ==============================

				// 检查参数设置
				checkParams();

				// 保存全局信息
				KVConfigUtil.write("project", globalMap);

				// 生成目标代码
				Code.create(database, globalMap);

				// 提示用户成功
				JOptionPane.showMessageDialog(null, "代码生成成功！", "温馨提示", JOptionPane.INFORMATION_MESSAGE);

				// 打开生成目录
				try {
					Desktop.getDesktop().open(new File(textField_1.getText()));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		button_2.setBounds(370, 269, 80, 32);
		codeBuilderFrame.getContentPane().add(button_2);
	}

	/**
	 * 功能说明：检查参数设置
	 */
	private void checkParams() {
		// 检查参数设置
		for (String key : globalMap.keySet()) {
			logger.info("读取全局替换参数：" + "[" + key + "] - " + globalMap.get(key));
			if (Alias.isBlank(globalMap.get(key))) {
				JOptionPane.showMessageDialog(null, "请您将参数填写完整！", "温馨提示", JOptionPane.WARNING_MESSAGE);
				return;
			}
		}
	}

}
